﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ERPWinFormWork.Test.Test.Dtos;
using ERPWinFormWork.Test.TestCode;
using Newtonsoft.Json;

namespace ERPWinFormWork.Test
{
    /// <summary>
    /// 采购核价详情窗体
    /// </summary>
    public partial class ProcurementPricingDetail : Form
    {
        /// <summary>
        /// 采购核价编号
        /// </summary>
        private string _pricingNode;

        /// <summary>
        /// 采购核价ID
        /// </summary>
        private int? _pricingId;

        /// <summary>
        /// API客户端
        /// </summary>
        private ApiClient _apiClient;

        /// <summary>
        /// 采购核价主表数据
        /// </summary>
        private GetProcurement_PricingDtos _pricingData;

        public ProcurementPricingDetail()
        {
            InitializeComponent();
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);
        }

        public ProcurementPricingDetail(string pricingNode)
        {
            InitializeComponent();
            _pricingNode = pricingNode;
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);

            if (textpricingNode != null)
            {
                textpricingNode.Text = _pricingNode ?? string.Empty;
            }


            InitializeGridAndEvents();

            // 在窗体完成加载后再请求数据，确保控件已初始化
            this.Load += async (s, e) =>
            {
                await LoadProcurementPricingDataAsync();
                await LoadMaterialDataAsync();
            };
        }

        public ProcurementPricingDetail(int id)
        {
            InitializeComponent();
            _pricingId = id;
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);

            InitializeGridAndEvents();

            this.Load += async (s, e) =>
            {
                await LoadProcurementPricingDataByIdAsync();
                // 通过ID获取采购核价数据后，再获取物料数据
                if (!string.IsNullOrEmpty(_pricingNode))
                {
                    await LoadMaterialDataAsync();
                }
            };
        }

        /// <summary>
        /// 初始化表格与事件
        /// </summary>
        private void InitializeGridAndEvents()
        {
            ConfigureMaterialGrid();

            if (dgvmater != null)
            {
                dgvmater.DataBindingComplete += async (s, e) =>
                {
                    var grid = dgvmater;
                    int colCount = grid.Columns.Count;
                    if (grid.Columns.Contains("colTaxRate")) grid.Columns["colTaxRate"].DisplayIndex = Math.Max(0, colCount - 3);
                    if (grid.Columns.Contains("colNewUntaxedPrice")) grid.Columns["colNewUntaxedPrice"].DisplayIndex = Math.Max(0, colCount - 2);
                    if (grid.Columns.Contains("colNewTaxedPrice")) grid.Columns["colNewTaxedPrice"].DisplayIndex = Math.Max(0, colCount - 1);

                    // 数据绑定完成后，处理物料数据（设置税率、行配色等）
                    ProcessMaterialDataAfterBinding();

                    // 数据绑定完成后，加载新价格数据并反填
                    await LoadNewPricesAndFillBack();
                };
            }
        }

        /// <summary>
        /// 配置物料表格样式与列
        /// </summary>
        private void ConfigureMaterialGrid()
        {
            if (dgvmater == null) return;
            var grid = dgvmater;
            grid.AllowUserToAddRows = false;

            if (!grid.Columns.Contains("colTaxRate"))
            {
                var colTaxRate = new DataGridViewTextBoxColumn
                {
                    Name = "colTaxRate",
                    HeaderText = "税率%",
                    ValueType = typeof(int),
                    Width = 70,
                    ReadOnly = true
                };
                colTaxRate.DefaultCellStyle.Format = "N0";
                colTaxRate.DefaultCellStyle.NullValue = string.Empty;
                grid.Columns.Add(colTaxRate);
            }

            // 新未税价格列
            if (!grid.Columns.Contains("colNewUntaxedPrice"))
            {
                var colUntaxed = new DataGridViewTextBoxColumn
                {
                    Name = "colNewUntaxedPrice",
                    HeaderText = "新未税价格",
                    ValueType = typeof(decimal),
                    Width = 100,
                    ReadOnly = true
                };
                colUntaxed.DefaultCellStyle.Format = "N2";
                colUntaxed.DefaultCellStyle.NullValue = string.Empty;
                grid.Columns.Add(colUntaxed);
            }

            // 新含税价格列
            if (!grid.Columns.Contains("colNewTaxedPrice"))
            {
                var colTaxed = new DataGridViewTextBoxColumn
                {
                    Name = "colNewTaxedPrice",
                    HeaderText = "新含税价格",
                    ValueType = typeof(decimal),
                    Width = 100,
                    ReadOnly = true
                };
                colTaxed.DefaultCellStyle.Format = "N2";
                colTaxed.DefaultCellStyle.NullValue = string.Empty;
                grid.Columns.Add(colTaxed);
            }

            grid.EnableHeadersVisualStyles = false;
            grid.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(83, 196, 242);
            grid.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
            grid.ColumnHeadersDefaultCellStyle.Font = new Font("微软雅黑", 9F, FontStyle.Bold);
            grid.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(245, 245, 245);
        }

        /// <summary>
        /// 根据编号加载采购核价主表信息并反填（Task 版本）
        /// </summary>
        private async Task LoadProcurementPricingDataAsync()
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                var parameters = new Dictionary<string, string> { { "pricingNode", _pricingNode } };
                // 接口返回 data 为数组，因此按列表接收
                var result = await _apiClient.GetAsync<TestApiResult<List<GetProcurement_PricingDtos>>>(
                    "api/Read/GetProcurementByPricingNode", parameters);

                if (result != null && result.code == 200 && result.data != null && result.data.Count > 0)
                {
                    _pricingData = result.data.FirstOrDefault();
                    FillFormData();
                }
                else
                {
                    MessageBox.Show($"获取采购核价详情失败：{result?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载采购核价详情时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 根据采购核价ID加载采购核价详情数据
        /// </summary>
        private async Task LoadProcurementPricingDataByIdAsync()
        {
            if (!_pricingId.HasValue) return;
            try
            {
                this.Cursor = Cursors.WaitCursor;

                // 使用正确的API接口：根据ID获取采购核价详情
                var parameters = new Dictionary<string, string> { { "id", _pricingId.Value.ToString() } };
                var result = await _apiClient.GetAsync<TestApiResult<List<GetProcurement_PricingDtos>>>(
                    "api/Read/GetProcurementById", parameters);

                if (result != null && result.code == 200 && result.data != null && result.data.Count > 0)
                {
                    _pricingData = result.data.FirstOrDefault();
                    FillFormData();

                    // 如果成功获取到采购核价数据，更新采购核价编号
                    if (_pricingData != null && !string.IsNullOrEmpty(_pricingData.PricingNode))
                    {
                        _pricingNode = _pricingData.PricingNode;
                    }
                }
                else
                {
                    MessageBox.Show($"获取采购核价详情失败：{result?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载采购核价详情时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }



        private void FillFormData()
        {
            if (_pricingData == null) return;
            if (textpricingNode != null) textpricingNode.Text = _pricingData.PricingNode ?? string.Empty;
            if (textpricingName != null) textpricingName.Text = _pricingData.PricingName ?? string.Empty;
            if (textpricing_Date != null) textpricing_Date.Text = _pricingData.Pricing_Date.ToString("yyyy-MM-dd");
            if (textsupplierName != null) textsupplierName.Text = _pricingData.SupplierName ?? string.Empty;
            if (texttax_Rate != null) texttax_Rate.Text = _pricingData.Tax_Rate.ToString();
            if (textnotes != null) textnotes.Text = _pricingData.Notes ?? string.Empty;
        }

        /// <summary>
        /// 加载并绑定物料明细数据（Task 版本）
        /// </summary>
        private async Task LoadMaterialDataAsync()
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                var parameters = new Dictionary<string, string> { { "pricingNode", _pricingNode } };
                var result = await _apiClient.GetAsync<TestApiResult<List<Material_TableDtos>>>(
                    "api/Read/FindMaterialByProcurementNode", parameters);

                if (result != null && result.code == 200 && result.data != null)
                {
                    var list = result.data;
                    this.Invoke(new Action(() => BindMaterialDataToGrid(list)));
                }
                else
                {
                    MessageBox.Show($"获取物料数据失败：{result?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载物料数据时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }





        /// <summary>
        /// 绑定物料数据到表格并设置基础信息
        /// </summary>
        private void BindMaterialDataToGrid(List<Material_TableDtos> materialList)
        {
            if (dgvmater == null) return;

            // 设置数据源
            dgvmater.DataSource = new BindingList<Material_TableDtos>(materialList ?? new List<Material_TableDtos>());

        }

        /// <summary>
        /// 在数据绑定完成后处理物料数据（设置税率、行配色等）
        /// </summary>
        private void ProcessMaterialDataAfterBinding()
        {
            if (dgvmater == null || dgvmater.Rows.Count == 0) return;

            // 设置税率列值及行配色
            if (dgvmater.Columns.Contains("colTaxRate"))
            {
                // 采购核价统一税率：必须与上方一致，不设置默认值
                int? taxRate = null;
                if (_pricingData != null && _pricingData.Tax_Rate > 0) taxRate = _pricingData.Tax_Rate;
                else if (texttax_Rate != null && int.TryParse(texttax_Rate.Text, out var tr) && tr >= 0) taxRate = tr;

                foreach (DataGridViewRow row in dgvmater.Rows)
                {
                    if (row.DataBoundItem is Material_TableDtos material)
                    {
                        // 税率：使用采购核价统一税率（若无则置空）
                        row.Cells["colTaxRate"].Value = taxRate.HasValue ? (object)taxRate.Value : null;

                        // 行配色：13%税率的行使用特殊背景色
                        if (taxRate.HasValue && taxRate.Value == 13)
                        {
                            row.DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 240);
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 加载并填充新价格数据（根据采购核价编号）
        /// </summary>
        private async Task LoadAndFillNewPricesByNodeAsync()
        {
            // 这个方法现在由 LoadNewPricesAndFillBack 替代
            await LoadNewPricesAndFillBack();
        }

        /// <summary>
        /// 加载新价格数据并反填到表格（参考UpdateProcurement_Pricing.cs的逻辑）
        /// </summary>
        private async Task LoadNewPricesAndFillBack()
        {
            try
            {


                if (string.IsNullOrEmpty(_pricingNode) || dgvmater == null)
                {
                    Console.WriteLine("采购核价编号为空或表格为空，退出");
                    return;
                }

                // 根据采购核价编号查询新价格数据（API返回的是数组）
                var endpoint = $"api/Read/FindPriceByProcurementNode?pricingNode={_pricingNode}";
                Console.WriteLine($"调用API: {endpoint}");

                var priceResponse = await _apiClient.GetAsync<TestApiResult<List<GetProcurement_PricingDtos>>>(
                    endpoint: endpoint,
                    parameters: null
                );

                if (priceResponse != null && priceResponse.code == 200 && priceResponse.data != null)
                {
                    var priceDataList = priceResponse.data;

                    // 打印前几条价格数据用于调试
                    for (int i = 0; i < Math.Min(3, priceDataList.Count); i++)
                    {
                        var priceItem = priceDataList[i];

                    }

                    int updatedCount = 0;
                    int notFoundCount = 0;

                    // 遍历表格中的物料行，根据物料Id匹配并反填新价格
                    foreach (DataGridViewRow row in dgvmater.Rows)
                    {
                        if (row.DataBoundItem is Material_TableDtos material)
                        {

                            // 在价格数据列表中查找匹配的物料
                            var matchingPriceData = priceDataList.FirstOrDefault(p => p.Material_Id == material.Id);

                            if (matchingPriceData != null)
                            {
                                // 反填新未税价格到对应的列
                                if (dgvmater.Columns.Contains("colNewUntaxedPrice"))
                                {
                                    var untaxedValue = matchingPriceData.Untaxed_Price > 0 ? matchingPriceData.Untaxed_Price.ToString("F2") : string.Empty;
                                    row.Cells["colNewUntaxedPrice"].Value = untaxedValue;
                                    Console.WriteLine($"  设置新未税价格: {untaxedValue}");
                                }

                                // 反填新含税价格到对应的列
                                if (dgvmater.Columns.Contains("colNewTaxedPrice"))
                                {
                                    var taxedValue = matchingPriceData.Taxed_Price > 0 ? matchingPriceData.Taxed_Price.ToString("F2") : string.Empty;
                                    row.Cells["colNewTaxedPrice"].Value = taxedValue;
                                    Console.WriteLine($"  设置新含税价格: {taxedValue}");
                                }


                                updatedCount++;
                            }
                            else
                            {
                                // 如果没有找到新价格数据，使用原价格作为默认值
                                if (dgvmater.Columns.Contains("colNewUntaxedPrice"))
                                {
                                    var originalUntaxed = material.OidUntaxedPrice ?? 0m;
                                    row.Cells["colNewUntaxedPrice"].Value = originalUntaxed > 0 ? originalUntaxed.ToString("F2") : string.Empty;
                                }

                                if (dgvmater.Columns.Contains("colNewTaxedPrice"))
                                {
                                    var originalTaxed = material.OidIncludingTax ?? 0m;
                                    row.Cells["colNewTaxedPrice"].Value = originalTaxed > 0 ? originalTaxed.ToString("F2") : string.Empty;
                                }


                                notFoundCount++;
                            }
                        }
                    }

                }
                else
                {
                    // 如果API调用失败，使用原价格作为默认值
                    SetOriginalPricesAsDefault();
                }
            }
            catch (Exception ex)
            {

                // 异常情况下，使用原价格作为默认值
                SetOriginalPricesAsDefault();
            }
        }

        /// <summary>
        /// 根据采购核价编号获取新价格数据
        /// </summary>
        private async Task LoadNewPricesByPricingNodeAsync()
        {
            if (string.IsNullOrEmpty(_pricingNode)) return;

            try
            {
                // 调用API获取新价格数据
                var parameters = new Dictionary<string, string> { { "pricingNode", _pricingNode } };
                var result = await _apiClient.GetAsync<TestApiResult<List<GetProcurement_PricingDtos>>>(
                    "api/Read/FindPriceByProcurementNode", parameters);

                if (result != null && result.code == 200 && result.data != null && result.data.Count > 0)
                {
                    // 更新表格中的新价格数据
                    UpdateNewPricesInGrid(result.data);
                }
                else
                {
                    // 如果API调用失败，尝试从物料数据中获取价格信息
                    await LoadNewPricesFromMaterialDataAsync();
                }
            }
            catch (Exception ex)
            {
                // 如果新价格API调用失败，尝试从物料数据中获取
                await LoadNewPricesFromMaterialDataAsync();
            }
        }




        /// <summary>
        /// 从物料数据中加载新价格信息（备用方案）
        /// </summary>
        private async Task LoadNewPricesFromMaterialDataAsync()
        {
            try
            {
                // 重新加载物料数据以确保获取最新价格
                await LoadMaterialDataAsync();
            }
            catch (Exception ex)
            {
                // 静默处理，避免影响主要功能
            }
        }

        /// <summary>
        /// 从物料数据中提取并反填价格信息到表格（参考UpdateInInspection.cs的逻辑）
        /// </summary>
        private void ExtractAndFillPricesFromMaterialData(List<Material_TableDtos> materialList)
        {
            if (dgvmater == null || materialList == null || materialList.Count == 0) return;

            int updatedCount = 0;
            int notFoundCount = 0;

            // 遍历表格中的物料行，从物料数据中提取价格信息并反填
            foreach (DataGridViewRow row in dgvmater.Rows)
            {
                if (row.DataBoundItem is Material_TableDtos material)
                {
                    // 在物料数据列表中查找匹配的物料
                    var matchingMaterial = materialList.FirstOrDefault(m => m.Id == material.Id);

                    if (matchingMaterial != null)
                    {
                        // 反填新未税价格到对应的列
                        if (dgvmater.Columns.Contains("colNewUntaxedPrice"))
                        {
                            var newUntaxedValue = GetMaterialPriceValue(matchingMaterial, "NewUntaxedPrice", "Untaxed_Price");
                            row.Cells["colNewUntaxedPrice"].Value = newUntaxedValue;
                        }

                        // 反填新含税价格到对应的列
                        if (dgvmater.Columns.Contains("colNewTaxedPrice"))
                        {
                            var newTaxedValue = GetMaterialPriceValue(matchingMaterial, "NewTaxedPrice", "Taxed_Price");
                            row.Cells["colNewTaxedPrice"].Value = newTaxedValue;
                        }

                        updatedCount++;
                    }
                    else
                    {
                        notFoundCount++;
                    }
                }
            }
        }

        /// <summary>
        /// 获取物料的价格值（支持多种字段命名）
        /// </summary>
        private object GetMaterialPriceValue(Material_TableDtos material, string primaryField, string fallbackField)
        {
            try
            {
                // 优先尝试主要字段
                var primaryValue = material.GetType().GetProperty(primaryField)?.GetValue(material);
                if (primaryValue is decimal primaryDecimal && primaryDecimal > 0)
                {
                    return primaryDecimal;
                }

                // 如果主要字段没有值，尝试备用字段
                var fallbackValue = material.GetType().GetProperty(fallbackField)?.GetValue(material);
                if (fallbackValue is decimal fallbackDecimal && fallbackDecimal > 0)
                {
                    return fallbackDecimal;
                }

                return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 设置原价格作为默认值
        /// </summary>
        private void SetOriginalPricesAsDefault()
        {
            if (dgvmater == null || dgvmater.Rows.Count == 0) return;

            Console.WriteLine("使用原价格作为默认值");
            foreach (DataGridViewRow row in dgvmater.Rows)
            {
                if (row.DataBoundItem is Material_TableDtos material)
                {
                    if (dgvmater.Columns.Contains("colNewUntaxedPrice"))
                    {
                        var originalUntaxed = material.OidUntaxedPrice ?? 0m;
                        row.Cells["colNewUntaxedPrice"].Value = originalUntaxed > 0 ? originalUntaxed.ToString("F2") : string.Empty;
                    }

                    if (dgvmater.Columns.Contains("colNewTaxedPrice"))
                    {
                        var originalTaxed = material.OidIncludingTax ?? 0m;
                        row.Cells["colNewTaxedPrice"].Value = originalTaxed > 0 ? originalTaxed.ToString("F2") : string.Empty;
                    }
                }
            }
        }

        /// <summary>
        /// 更新表格中的新价格数据（参考UpdateInInspection.cs的反填逻辑）
        /// </summary>
        private void UpdateNewPricesInGrid(List<GetProcurement_PricingDtos> newPriceData)
        {
            if (dgvmater == null || newPriceData == null || newPriceData.Count == 0) return;

            // 创建价格查找字典，以物料ID为键
            var priceLookup = newPriceData.ToDictionary(x => x.Material_Id, x => x);

            int updatedCount = 0;
            int notFoundCount = 0;

            // 遍历表格中的物料行，根据物料ID匹配并反填新价格
            foreach (DataGridViewRow row in dgvmater.Rows)
            {
                if (row.DataBoundItem is Material_TableDtos material)
                {
                    // 在价格数据列表中查找匹配的物料
                    if (priceLookup.TryGetValue(material.Id, out var priceInfo))
                    {
                        // 反填新未税价格到对应的列
                        if (dgvmater.Columns.Contains("colNewUntaxedPrice"))
                        {
                            var newUntaxedValue = priceInfo.Untaxed_Price > 0 ? priceInfo.Untaxed_Price.ToString("F2") : string.Empty;
                            row.Cells["colNewUntaxedPrice"].Value = newUntaxedValue;
                        }

                        // 反填新含税价格到对应的列
                        if (dgvmater.Columns.Contains("colNewTaxedPrice"))
                        {
                            var newTaxedValue = priceInfo.Taxed_Price > 0 ? priceInfo.Taxed_Price.ToString("F2") : string.Empty;
                            row.Cells["colNewTaxedPrice"].Value = newTaxedValue;
                        }

                        updatedCount++;
                    }
                    else
                    {
                        notFoundCount++;
                    }
                }
            }
        }




        /// <summary>
        /// 刷新所有数据
        /// </summary>
        public async void RefreshData()
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                if (!string.IsNullOrEmpty(_pricingNode))
                {
                    await LoadProcurementPricingDataAsync();
                    await LoadMaterialDataAsync();
                }
                else if (_pricingId.HasValue)
                {
                    await LoadProcurementPricingDataByIdAsync();
                    // 通过ID获取采购核价数据后，再获取物料数据
                    if (!string.IsNullOrEmpty(_pricingNode))
                    {
                        await LoadMaterialDataAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"刷新数据时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

    }
}
